from django.shortcuts import render,redirect
from django.http import JsonResponse,HttpResponse
import random
import string
from django.core.mail import send_mail
from django_redis import get_redis_connection
from django.views.decorators.http import require_http_methods,require_POST,require_GET
from .forms import UserRegistrationForm,UserLoginForm,PubForm
from django.core.cache import cache
from .models import UserInfo,BlogCategory,Blog,BlogComment
from django.contrib.auth import login,logout
from django.contrib.auth.decorators import login_required
from django.db.models import Q


# Create your views here.
def index(request):
    blogs = Blog.objects.all()
    return render(request, 'index.html',context={'blogs':blogs})


def blog_detail(request,blog_id):
    # 从数据库取出对应的blog传递给前端进行展示
    blog = Blog.objects.filter(id=blog_id).first()
    content = {'blog':blog}
    return render(request, 'blog_detail.html',context=content)


@require_http_methods(["GET", "POST"])
@login_required(login_url='/app1/login')
def pub_blog(request):
    if request.method == "POST":
        form = PubForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            category = form.cleaned_data.get('category')
            blog = Blog.objects.create(title=title,content=content,category_id=category,author_id=request.user.id)
            return JsonResponse({'code': 200, 'msg': '发布成功','data':{'blog_id':blog.id}})
        else:
            print(form.errors)
            return JsonResponse({'code': 400, 'msg': '参数错误'})

    else:
        categories = BlogCategory.objects.all()
        return render(request, 'pub_blog.html',context={'categories':categories})



##登录注册功能
@require_http_methods(["GET", "POST"])
def bloglogin(request):
    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember_me = form.cleaned_data.get('rememberMe')
            # 检查用户是否存在
            user = UserInfo.objects.filter(email=email).first()
            if user:
                # 验证密码
                if user.password == password:
                    # 登录成功
                    login(request, user)  # 使用 Django 的登录方法，将用户信息保存到 session
                    request.session['_auth_user_id'] = user.id
                    # 处理 "记住我" 功能：设置 session 过期时间
                    if not remember_me:
                        request.session.set_expiry(0)  # 浏览器关闭时会话结束时过期
                    return redirect('app1:index')  # 跳转到首页
                else:
                    # 密码错误
                    # form.add_error('password', '密码错误，请重新输入')
                    print('密码错误，请重新输入')
                    return redirect('app1:bloglogin')
            else:
                # 用户不存在
                # form.add_error('email', '用户不存在，请检查邮箱')
                print('用户不存在，请检查邮箱')
                return redirect('app1:bloglogin')
        # return render(request, 'login.html', {'form': form})
    return render(request, 'login.html')


def logout_view(request):
    logout(request)  # 注销用户
    return redirect('app1:bloglogin')  # 重定向到登录页



@require_http_methods(["GET", "POST"])
def register(request):
    if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            # 获取表单数据
            username = form.cleaned_data.get('username')
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            UserInfo.objects.create(
                username=username,
                email=email,
                password=password,
            )
            return redirect('app1:bloglogin')
        print(form.errors)
        return redirect('app1:register')
    return render(request, 'register.html')

#邮箱发送验证码
def send_verification_email(request):

    """ 发送邮箱验证码 """
    email = request.POST.get('email')  # 前端传来的邮箱
    if not email:
        return JsonResponse({'code': 400, 'msg': '邮箱不能为空'})
    # 生成4位验证码
    code = ''.join(random.choices(string.digits, k=4))
    # 发送内容
    subject = "jw博客注册验证码"
    message = f"您的验证码是 {code}，请勿泄露。"
    send_mail(
        subject,
        message,
        recipient_list=[email],  # 收件人
        from_email=None,  # 这里可以直接写 None，会自动使用 `DEFAULT_FROM_EMAIL`
        )
    # 发送后将验证码存入redis
    #方法1：
    # 获取 Redis 连接
    redis_conn = get_redis_connection()
    # 将验证码存储到 Redis，设置过期时间（例如，60秒）
    redis_conn.set(email, code, ex=60)
    #方法2
    # cache.set(email, code, timeout=60)

    return JsonResponse({'code': 200, 'msg': '验证码已发送'})

@require_POST #相当于@require_http_methods(["POST"])
@login_required(login_url='/app1/login')
def pub_comment(request):
    content = request.POST.get('content')
    blog_id = request.POST.get('blog_id')
    # 将评论等相关数据存储在表BlogComment中
    BlogComment.objects.create(content=content,blog_id=blog_id,Commenter=request.user)
    return redirect('app1:blog_detail', blog_id=blog_id)


@require_GET #相当于@require_http_methods(["GET"])
def search(request):
    #/app1/search?kw=
    kw = request.GET.get('kw')
    blogs = Blog.objects.filter(Q(title__icontains=kw) | Q(content__icontains=kw)).all()
    return render(request, 'index.html',context={'blogs':blogs})
